<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Crypt;
use DB;

class LoginController extends Controller
{
    public function login()
    {
    	return view('admin.login.login');
    }

    public function dologin(Request $request)
    {
    	//验证验证码
    	$scode = session('milkcaptcha');
    	$rcode = $request ->input('captcha');
    	if($scode != $rcode)
    	{
    		return back() ->with(['info' => '验证码错误']);
    	}

    	//验证输入规则
    	$this -> validate($request,
    		['email' => 'required|email',
    		'password' => 'required'
    		],[
    		'email.required' => '邮箱不能为空',
    		'email.email' => '邮箱格式不正确',
    		'password.required' => '密码不能为空'
    		]);
    	$data = $request ->except('_token');

    	//查询数据库
    	$res = DB::table('users') -> where('email',$data['email']) ->first();
        // dd($res);

    	$password = Crypt::decrypt($res-> password);
    	if($password == $data['password'])
    	{
    		session(['master'=>$res]);
    		return redirect('/admin/index')-> with(['info' => '登录成功']);
    		//把用户的信息存入session,方便中间件判断
    		
    		
    	}else
    	{
    		return back() -> with(['info' => '账户或密码错误']);
    	}
    		

    }
    public function logout()
    {
    	//清除session中的用户信息
    	session()->forget('master');
    	return redirect('/admin/login') ->with(['info' =>'退出成功']);
    }


    	
}
